import {createSql} from "./index";
import type {Tree} from "../types";

const tableName = "t_tree";

export const queryList = (groupId) =>
    createSql<Tree[]>('SELECT * FROM ' + tableName + ' WHERE groupId = ? ORDER BY `rank` ASC',[groupId]);

export async function getRank(){
    const TreeList = await createSql<Tree[]>('SELECT * FROM ' + tableName + ' ORDER BY `rank` DESC LIMIT 1')
    return TreeList.length > 0 ? TreeList[0].rank + 1 : 1;
}

export const insert = async (data: Tree) =>{
    return  createSql<Tree[]>(
        'INSERT INTO '+ tableName + ' (id, `index`, tree,risk,rate,groupId ,createTime,`rank`) VALUES ( ?,?,?,?,?,?,?,?)',
        [data.id, data.index, data.tree,data.risk,data.rate,data.groupId,data.createTime,data.rank]
    );
}
export const deleteById = (id: string) =>{
    return createSql<Tree[]>(' DELETE FROM '+ tableName + ' WHERE id = ?', [id]);
}

export const update = async (data: Tree) =>{
    return createSql<Tree[]>(
        'UPDATE '+ tableName + ' SET `index` = ?, tree = ?,risk = ? WHERE id = ?',
        [data.index, data.tree, data.risk, data.id]
    );
}

export const queryById = (id) =>
    createSql<Tree[]>('SELECT * FROM ' + tableName + ' WHERE id = ?',[id]);

export const queryNotice = () =>
    createSql<Tree[]>('SELECT * FROM '+ tableName +' WHERE risk != \'\'');
export default {
    queryList,
    insert,
    deleteById,
    getRank,
    update,
    queryById,
    queryNotice
}
